package com.getword.web.controller;

import com.getword.domain.Comments;
import com.getword.domain.Reply;
import com.getword.domain.User;
import com.getword.service.CommentsService;
import com.getword.utils.SpringContextUtil;
import com.getword.web.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/comments")
public class ApiCommentsController {
    @Autowired
    private CommentsService commentsService;

    @GetMapping("/getInfo")
    public Result query(String articleId){
        System.out.println(articleId);
        return commentsService.getCommentsByArticleId(articleId);
    }

    /**
     * 参数：articleId, content
     * @param comments
     * @return
     */
    @PostMapping
    public Result create(Comments comments){
        User user = SpringContextUtil.getLoginUser();
        comments.setUser(user);
        comments.setTime(new Date());
        return commentsService.saveComments(comments);
    }

    /**
     * 添加回复，本质是更新Comments，更新replyList字段
     * @param reply
     * @return
     */
    @PostMapping("/addReply")
    public Result addReply(Reply reply, String commentId, HttpServletRequest request){
        reply.setId(UUID.randomUUID().toString());
        reply.setTime(new Date());
        User user = SpringContextUtil.getLoginUser();
        Map<String, Object> from = new HashMap<>();
        from.put("id", user.getId());
        from.put("username", user.getUsername());
        reply.setFrom(from);
        return commentsService.saveReply(reply, commentId);
    }
}
